package com.seocoo.worker.user.model;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.text.TextUtils;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.seocoo.worker.base.entity.EFile;
import com.seocoo.worker.base.entity.EUserInfoBean;
import com.seocoo.worker.base.entity.EVersion;
import com.seocoo.worker.base.http.BasePageRsp;
import com.seocoo.worker.base.http.BaseRsp;
import com.seocoo.worker.base.http.ReqUploadFile;
import com.seocoo.worker.home.ReqDwmVersion;
import com.seocoo.worker.user.entity.EIntgral;
import com.seocoo.worker.user.entity.EPromo;
import com.seocoo.worker.user.entity.EPromoList;
import com.seocoo.worker.user.login.entity.ECraftsmanInfo;
import com.seocoo.worker.user.login.model.ReqPlatform;
import com.seocoo.worker.user.model.request.ReqApplyMeasure;
import com.seocoo.worker.user.model.request.ReqCraftsmanInfo;
import com.seocoo.worker.user.model.request.ReqIntegralChange;
import com.seocoo.worker.user.model.request.ReqPromo;
import com.seocoo.worker.user.model.request.ReqPromoList;
import com.seocoo.worker.user.model.request.ReqRefreshLocation;
import com.seocoo.worker.user.model.request.ReqRule;
import com.seocoo.worker.user.model.request.ReqUserInfo;
import com.seocoo.worker.user.model.request.ReqUserModify;
import com.sfh.lib.AppCacheManager;
import com.sfh.lib.HandleException;
import com.sfh.lib.IResult;
import com.sfh.lib.IResultSuccess;
import com.sfh.lib.IResultSuccessNoFail;
import com.sfh.lib.mvvm.BaseViewModel;
import com.sfh.lib.ui.DialogBuilder;

import java.io.File;
import java.util.concurrent.Callable;

public class UserModel extends BaseViewModel {

    public void getUserInfo() {
        this.execute(new ReqUserInfo(), (IResultSuccessNoFail<BaseRsp<EUserInfoBean>>) eUserInfoBeanBaseRsp -> {
            if (eUserInfoBeanBaseRsp.success()) {
                setValue("onUserInfo", eUserInfoBeanBaseRsp.getData());
            }
        });
    }

    /***
     * 修改头像
     * @param requestCode
     * @param path
     */
    public void editAvatar(int requestCode, String path) {
        this.execute(false, () -> {
            BaseRsp<EFile> baseRsp = new ReqUploadFile(new File(path)).call();
            if (baseRsp.success()) {

                return new ReqUserModify().setAvatar(baseRsp.getData().getFileName()).call();
            }
            return baseRsp;
        }, infoBean -> {
            if (infoBean.success()) {
                showToast("修改头像成功！");
                //查询个人信息
                getUserInfo();
            } else {
                showDialogToast(infoBean.getMsg());
            }
        });
    }

    /***
     * 修改昵称
     * @param nickName
     */
    public void editNickName(String nickName) {
        this.execute(false, new ReqUserModify().setNickName(nickName), baseRsp -> {
            if (baseRsp.success()) {
                showToast("修改成功！");
                setValue("onEditNickNameSuccess");
            } else {
                showDialogToast(baseRsp.getMsg());
            }
        });
    }

    /***
     * 积分变化
     */
    public void queryIntegralChange(int nowPage) {
        this.execute(new ReqIntegralChange(nowPage), new IResult<BasePageRsp<EIntgral>>() {
            @Override
            public void onFail(HandleException e) {
                setValue("onPageSuccess");
            }

            @Override
            public void onSuccess(BasePageRsp<EIntgral> eIntgralBasePageRsp) throws Exception {
                setValue("onPageSuccess", eIntgralBasePageRsp);
            }
        });
    }


    public void refreshLocation(Context context) {

        AMapLocationClient mLocationClient = new AMapLocationClient(context.getApplicationContext());
        //初始化定位参数
        AMapLocationClientOption mLocationOption = new AMapLocationClientOption();
        //设置定位模式为Hight_Accuracy高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);
        //设置是否只定位一次,默认为false
        mLocationOption.setOnceLocation(true);

        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位
        mLocationClient.setLocationListener(amapLocation -> {

            if (amapLocation.getErrorCode() == 0) {
                //更新工匠的位置信息
                execute(new ReqRefreshLocation(amapLocation.getLatitude(), amapLocation.getLongitude()));
            }
        });
        mLocationClient.startLocation();

    }

    /***
     *  平台电话
     */
    public void getCallPhone(Context context) {

        this.execute(true, new ReqPlatform(), baseRsp -> {
            if (baseRsp.success()) {

                DialogBuilder builder = new DialogBuilder();
                builder.setMessage(baseRsp.getData().hotline);
                builder.setHideCancel(true);
                builder.setOKTextListener("立即呼叫", (dialog, which) -> {
                    dialog.dismiss();
                    Intent intent = new Intent(Intent.ACTION_DIAL);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    intent.setData(Uri.parse("tel:" + baseRsp.getData().hotline));
                    if (context.getPackageManager().resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY) != null) {
                        context.startActivity(intent);
                    } else {
                        Toast.makeText(context, "无法拨打电话，请检查应用权限设置", Toast.LENGTH_SHORT).show();
                    }
                });
                showDialog(builder);
            } else {
                showDialogToast(baseRsp.getMsg());
            }
        });
    }


    public void queryVersion() {
        this.execute(new ReqDwmVersion(), (IResultSuccessNoFail<BaseRsp<EVersion>>) eVersionBaseRsp -> {
            if (eVersionBaseRsp.success()) {
                setValue("onVersonDialog", eVersionBaseRsp.getData());
            }
        });
    }

    /***
     * 获取推广信息
     */
    public void queryPromo() {
        this.execute(true, new ReqPromo(), ePromoBaseRsp -> {
            if (ePromoBaseRsp.success()) {
                setValue("onPromo", ePromoBaseRsp.getData());
            } else {
                showDialogToast(ePromoBaseRsp.getMsg());
            }
        });
    }

    public void queryPromoList(String promoType) {
        this.execute(new ReqPromoList(promoType), (IResultSuccessNoFail<BasePageRsp<EPromoList>>) ePromoListBasePageRsp -> {
            if (ePromoListBasePageRsp.success()) {
                setValue("onPromoList", ePromoListBasePageRsp.getRootArray());
            } else {
                setValue("onPromoList");
            }
        });
    }

    //申请金牌工匠
    public void applyMeasure(ReqApplyMeasure req) {
        this.execute(false, req, new IResultSuccess<BaseRsp>() {
            @Override
            public void onSuccess(BaseRsp baseRsp) throws Exception {
                if (baseRsp.success()){
                    setValue("onApplyMeasure");
                }else{
                    showDialogToast(baseRsp.getMsg());
                }
            }
        });
    }

    //查询工匠申请信息
    public void queryCraftsmanInfo() {
        this.execute(false, new ReqCraftsmanInfo(), new IResultSuccess<BaseRsp<ECraftsmanInfo>>() {
            @Override
            public void onSuccess(BaseRsp<ECraftsmanInfo> baseRsp) throws Exception {
                if (baseRsp.success()){
                    setValue("onCraftsmanInfo",baseRsp.getData());
                }else{
                    showDialogToast(baseRsp.getMsg());
                }
            }
        });
    }


    /***
     * 查询规则 type 1-五星工匠抢单规则2-五星工匠升级规则3-申请为金牌工匠规则4-分销规则
     */
    public void queryRule(String type){
        this.execute(true, new ReqRule(type), new IResultSuccess<BaseRsp<String>>() {
            @Override
            public void onSuccess(BaseRsp<String> baseRsp) throws Exception {
                if (baseRsp.success()){
                    setValue("showRule",baseRsp.getData());
                }else{
                    showDialogToast(baseRsp.getMsg());
                }
            }
        });
    }
    public void queryRuleShow(String type){
        this.execute(new ReqRule(type), new IResultSuccess<BaseRsp<String>>() {
            @Override
            public void onSuccess(BaseRsp<String> baseRsp) throws Exception {
                if (baseRsp.success() && !TextUtils.isEmpty(baseRsp.getData())){
                    setValue("showRuleIcon");
                }
            }
        });
    }
}
